package com.example.fill.Test240126;

import java.util.Random;
import java.util.UUID;

public class Emitter implements Emi,Rec{
    Transaction transaction;
    Random random = new Random();

    public Emitter(Transaction transaction) {
        this.transaction = transaction;
    }

    class MyRunner implements Runnable {
        UUID uuid;

        public MyRunner(UUID uuid) {
            this.uuid = uuid;
        }

        @Override
        public void run() {
            System.out.println(uuid.toString() + "启动，处理中");
            int i = random.nextInt();
            if (i < 0.2f){
                return;
            }else if (i < 0.4f){
                uuid = UUID.randomUUID();
            }
            try {
                Thread.sleep( random.nextInt(1000)+300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(uuid.toString() + "处理完毕，回复请求");
            send(new byte[]{
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255),
                    (byte) random.nextInt(255)
            }, uuid);

        }
    };

    @Override
    public void send(byte[] b, UUID uuid) {
        transaction.receive(b,uuid);
    }

    @Override
    public void receive(byte[] b,UUID uuid) {
        System.out.println("收到请求"+System.currentTimeMillis()+"准备启动");
        new Thread(new MyRunner(uuid)).start();
    }
}
